using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using GraphAPI.Model;
using GraphAPI;

namespace GraphEditor
{
	public partial class PropertiesRelation : UserControl
	{
		public PropertiesRelation()
		{
			InitializeComponent();
		}

		Connection con;
		Graph graph;

		public void SetRelarion(Connection con, Graph graph)
		{
			this.con = con;
			this.graph = graph;

			txtName.Text = con.Text;
			
			if (con.Weight.Equals(double.NaN))
				txtWeigth.Text = "";
			else
				txtWeigth.Text = con.Weight.ToString();
			txtWeigth.BackColor = Color.White;

			txtCommentary.Text = con.Commentary;

			if (con.Oriented)
				btnRevert.Enabled = true;
			else
				btnRevert.Enabled = false;

			txtFrom.Text = con.Start.Text;
			txtTo.Text = con.End.Text;
		}

		private void txtName_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Enter)
			{
				con.Text = txtName.Text;
				txtName.SelectAll();
			}
		}

		private void txtName_Leave(object sender, EventArgs e)
		{
			con.Text = txtName.Text;
		}

		private void ReWeigth(string weight)
		{
			double res;

			if (txtWeigth.Text.Length == 0)
			{
				con.Weight = double.NaN;
				return;
			}

			try
			{
				res = double.Parse(weight);
				con.Weight = res;
				txtWeigth.SelectAll();
				txtWeigth.BackColor = Color.White;
			}
			catch
			{
				txtWeigth.BackColor = Color.Pink;
			}
		}

		private void txtWeigth_Leave(object sender, EventArgs e)
		{
			ReWeigth(txtWeigth.Text);
		}

		private void txtWeigth_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Escape)
			{
				txtWeigth.Text = con.Weight.ToString();
				return;
			}

			if (e.KeyCode == Keys.Enter)
				ReWeigth(txtWeigth.Text);
		}

		private void txtCommentary_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Escape)
			{
				txtCommentary.Text = con.Commentary;
				return;
			}

			con.Commentary = txtCommentary.Text;
		}


		private void btnRevert_Click(object sender, EventArgs e)
		{
			Vertex ver;
			ver = con.Start;
			con.Start = con.End;
			con.End = ver;

			Relation rel = con.Relation;
			rel.StartEntity = rel.EndEntity;
			rel.EndEntity = ver.Entity;

			graph.UpdateMatrixes();
			this.SetRelarion(con, graph);
		}

		private void txtCommentary_KeyUp(object sender, KeyEventArgs e)
		{
		
		}

	}
}













